import {REGISTER, REGISTER_SUBMIT} from "./const";
import {call, put, take} from "redux-saga/effects";
import {getCaptcha, register} from "../../services/api";
import {registerLoadingEndAction, registerLoadingStartAction} from "../loading/actionCreator";
import {GET_CAPTCHA} from "../login/const";
import {reloadAuthorized} from "../../utils/Authorized";
import {setAuthority, setToken} from "../../utils/authority";
import {registerAction} from "./actionCreator";

export default function* registerSaga() {
  while (true) {
    const {payload} = yield take(REGISTER_SUBMIT);
    yield put(registerLoadingStartAction());
    try {
      const {captcha, mobile, password} = payload;
      const newPayload = {
        mobile,
        code: captcha,
        username: mobile,
        password: password,
      };
      const rsp = yield call(register, newPayload);
      if (rsp.status === 'Created') {
        // todo
        yield put(registerAction({status: 'OK',}));
        reloadAuthorized();
        setToken(rsp.data.token);
      }
    } catch (e) {
      console.log(e);
    } finally {
      yield put(registerLoadingEndAction())
    }

  }
}
